using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Inspections.Commands;

/// <summary>
/// 设备点检计划创建命令。
/// </summary>
public sealed record CreateInspectionPlanCommand(EquipInspectionPlanDto Plan) : IRequest<IResult<bool>>;

internal sealed class CreateInspectionPlanCommandHandler(IRepository<EquipInspectionPlan> repo) : IRequestHandler<CreateInspectionPlanCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateInspectionPlanCommand request, CancellationToken cancellationToken)
    {
        // 同一种设备同一种点检类型只能创建一个。
        if (await repo.IsAnyAsync(m => m.MachineryId == request.Plan.MachineryId && m.InspectType == request.Plan.InspectType, cancellationToken))
        {
            return Result.Failure("同一种设备同一种点检类型只能创建一个");
        }

        var plan = request.Plan.Adapt<EquipInspectionPlan>();
        var ok = await repo.InsertAsync(plan, cancellationToken);
        return Result.From(ok);
    }
}
